package com.lr.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.openxml4j.util.ZipSecureFile;

import com.deepoove.poi.XWPFTemplate;

public class WordUtil {
	
	private WordUtil() {}
	
	/**
	 * 
	 * @param response 响应对象
	 * @param dataMap  替换的数据map
	 * @param dirPath  模版地址
	 * @param fileName 下载的word名字
	 */
	public static void createWordAndDownload(HttpServletResponse response,Map<String, Object> dataMap,String dirPath,String fileName) {
		InputStream fin = null;
		File f = null;
		ServletOutputStream out = null;
		try {
			ZipSecureFile.setMinInflateRatio(0.001);
			XWPFTemplate render = XWPFTemplate.compile(dirPath).render(dataMap);
	        render.writeToFile(fileName);
	        
	        f=new File(fileName);
	        fin = new FileInputStream(f);
	        response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
 
            out = response.getOutputStream();
            byte[] buffer = new byte[512];  // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(out!=null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fin!=null){
				try {
					fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(f != null) f.delete(); // 删除临时文件
		}
		
	}

	/**
	 * 生成word，存放在parent中
	 * @param response
	 * @param dataMap
	 * @param dirPath
	 * @param fileName
	 * @param parent  父目录
	 */
	public static void createWord(HttpServletResponse response,Map<String, Object> dataMap,String dirPath,String fileName,String parent) {
		try {
			ZipSecureFile.setMinInflateRatio(0.001);
			XWPFTemplate render = XWPFTemplate.compile(dirPath).render(dataMap);
			render.writeToFile(parent+File.separator+fileName);
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
